<template>
  <div id="userDetail">
    <h1 class="con-right-title">
      <i class="fa fa-reply" @click="cancel"></i>
      用户管理/{{ title }}
    </h1>
    <div class="form-box">
      <h3 class="title">
        基本信息
      </h3>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="ruleForm.userName" disabled />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="ruleForm.phonenumber" disabled />
            </el-form-item>
            <el-form-item label="登录账号" prop="loginName">
              <el-input v-model="ruleForm.loginName" disabled />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptName">
              <el-input v-model="ruleForm.deptName" @focus="showSelectDep">
                <el-button slot="append" icon="el-icon-search" />
              </el-input>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-switch
                v-model="ruleForm.status"
                active-value="0"
                inactive-value="1"
                active-color="#1DC8A4"
              ></el-switch>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="ruleForm.sex" placeholder="请选择用户性别">
                <el-option
                  v-for="item in sexList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色" prop="role">
              <el-checkbox-group v-model="ruleForm.roleIds">
                <el-checkbox
                  v-for="item in roleList"
                  :key="item.roleId"
                  name="role"
                  :label="item.roleId"
                  :disabled="item.status === 1"
                >
                  {{ item.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <h3 class="title">
          其他信息
        </h3>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="sub-button">
        <el-button type="success" plain @click="clearTag('default')">
          关闭
        </el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="submenu('ruleForm')"
        >
          保存
        </el-button>
      </div>
    </div>
    <!--选择部门组件-->
    <selectDepartment
      v-if="treeData.isShow"
      :dialog-data="treeData"
      @getDepartName="getDepartName"
    />
  </div>
</template>

<script>
import {
  checkRepeat,
  getDetail,
  addRole,
  editRole,
  editUsert
} from '@/api/system/user' // 接口
import selectDepartment from '@component/system/user/selectDepartment' // 选择部门
import { validateTelephone, validateEmail } from '@utils/validate'
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { clearTagMixins } from '@/mixins/clearTag'
export default {
  name: 'UserDetail',
  msg: '用户管理-详情页',
  mixins: [clearTagMixins],
  components: {
    selectDepartment
  },
  data() {
    var valiPhone = (rule, value, callback) => {
      if (validateTelephone(value)) {
        callback()
      } else {
        callback(new Error('请输入正确11位手机号码'))
      }
    }
    var valiEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      if (validateEmail(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }
    var valiPhoneAdd = (rule, value, callback) => {
      if (checkRepeat(value)) {
        let obj = {
          type: 'moblie',
          phonenumber: value
        }
        repeatPhone(
          obj,
          (response) => {
            if (response) {
              //true-无重复
              callback()
            } else {
              //false-有重复
              callback(new Error('该手机号码已使用'))
            }
          },
          (res) => {
            callback(new Error('校验失败'))
          }
        )
      } else {
        callback(new Error('请输入正确11位手机号码'))
      }
    }
    var valiEmailAdd = (rule, value, callback) => {
      if (validateEmail(value)) {
        let obj = {
          type: 'email',
          email: value
        }
        checkRepeat(
          obj,
          (response) => {
            if (response) {
              //true-无重复
              callback()
            } else {
              //false-有重复
              callback(new Error('该邮箱已使用'))
            }
          },
          (res) => {
            callback(new Error('校验失败'))
          }
        )
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }
    //校验登录账号是否重复
    var valiLoginNameAdd = (rule, value, callback) => {
      let obj = {
        type: 'DPACCOUNT',
        search: value
      }
      checkRepeat(
        obj,
        (response) => {
          if (response) {
            //true-无重复
            callback()
          } else {
            //false-有重复
            callback(new Error('该登录账号已使用'))
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      userId: '',
      loading: false,
      roleList: [], // 角色列表
      sexList: [], // 性别列表
      treeData: {
        isShow: false,
        selectId: []
      },
      ruleForm: {
        userName: '',
        phonenumber: '',
        loginName: '',
        dept: {
          deptName: ''
        },
        deptName: '',
        password: '',
        deptId: null,
        parentId: null,
        status: 1, //状态0正常,1停用
        roleIds: [],
        postIds: [],
        sex: '0',
        email: '',
        remark: ''
      },
      defaultForm: {
        userName: '',
        phonenumber: '',
        loginName: '',
        dept: {
          deptName: ''
        },
        deptName: '',
        password: '',
        deptId: null,
        parentId: null,
        status: 1, //状态0正常,1停用
        roleIds: [],
        postIds: [],
        sex: '0',
        email: '',
        remark: ''
      },
      passwordRules: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, message: '最少5个字符', trigger: 'blur' }
      ],
      emailRules: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: valiEmailAdd, trigger: 'blur' }
      ],
      phonenumberRules: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { validator: valiPhoneAdd, trigger: 'blur' }
      ],
      loginNameRules: [
        { required: true, message: '请输入登录账号', trigger: 'blur' },
        { min: 2, message: '最少 2 个字符', trigger: 'blur' },
        { validator: valiLoginNameAdd, trigger: 'blur' }
      ],
      rules: {
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: valiPhone, trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 2, message: '最少 2 个字符', trigger: 'blur' }
        ],
        remark: [{ max: 500, message: '最大长度500个字符', trigger: 'blur' }],
        password: [],
        email: [{ validator: valiEmail, trigger: 'blur' }],
        deptName: {
          required: true,
          message: '请选择归属部门',
          trigger: 'change'
        }
      }
    }
  },
  computed: {
    title() {
      return this.userId ? '修改用户' : '新增用户'
    }
  },
  watch: {
    // $route.path改变时，mounted()不执行,通过监听$route.path，执行进入页面方法
    '$route.path': 'init'
  },
  mounted() {
    this.init()
  },
  methods: {
    /* 进入页面执行的方法 */
    init() {
      //清空提示语，避免页面切换时互相影响
      this.$refs.ruleForm.clearValidate()
      this.ruleForm = { ...this.defaultForm }
      this.getSexList()
      this.userId = this.$route.params ? this.$route.params.id : ''
      if (this.userId) {
        //有this.userId，为编辑状态，获取表单信息
        this.loadingAccount()
      } else {
        this.rules.password = this.passwordRules
        this.rules.email = this.emailRules
        this.rules.phonenumber = this.phonenumberRules
        this.rules.loginName = this.loginNameRules
      }
      this.getUserRoles()
    },
    /* 获取表单信息 */
    async loadingAccount() {
      await getDetail(this.userId, (response) => {
        // 表单赋值
        let user = response
        this.ruleForm.userName = user.userName
        this.ruleForm.phonenumber = user.phonenumber
        this.ruleForm.loginName = user.loginName
        this.ruleForm.sex = user.sex
        this.ruleForm.email = user.email
        this.ruleForm.status = user.status
        this.ruleForm.remark = user.remark
        this.ruleForm.deptName = user.deptName
        this.ruleForm.deptId = user.deptId
        this.ruleForm.postIds = user.postIds
        this.ruleForm.roleIds = user.roleIds
        this.treeData.selectId = [user.deptId]
      })
    },
    /* 获取用户角色信息 */
    async getUserRoles() {
      if (this.userId) {
        //编辑
        await editRole(this.userId, (response) => {
          // 角色列表
          this.roleList = response
        })
      } else {
        //新增
        await addRole(this.userId, (response) => {
          // 角色列表
          this.roleList = response
        })
      }
    },
    /* 获取性别列表 */
    async getSexList() {
      this.sexList = await sysNormalDisable('sys_user_sex')
    },
    /* 显示选择部门弹窗 */
    showSelectDep() {
      this.treeData.isShow = true
    },
    /* 保存 */
    async submenu(formName) {
      this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          obj.userId = this.userId
          delete obj.deptName
          //编辑
          obj.dept.deptName = this.ruleForm.deptName
          editUsert(
            this.userId,
            obj,
            (response) => {
              this.$message.success('编辑成功')
              this.loading = false
            },
            (response) => {
              this.$message.warning(response.message)
              this.loading = false
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    /* 取消 */
    cancel() {
      let query = {
        mId: this.$route.query.mId
      }
      this.$router.push({ name: 'userList', query: query })
    },
    /* 获取组件中选中的部门 */
    getDepartName(node) {
      this.ruleForm.deptName = node.name
      this.ruleForm.deptId = node.id
      this.treeData.selectId = [node.id]
    }
  }
}
</script>

<style lang="less">
#userDetail {
  @import url('~@common/style/textarea.less');
  @blue: #0d1636;
  @green: #1dc8a4;
  .form-box {
    padding: 0 30px;
  }
}
</style>
